<?php

class Db {
  
  private static $connection;

  private function __construct() {
    if (!self::$connection) {
        self::$connection = mysqli_connect('localhost','root','','survey');
        mysqli_set_charset(self::$connection, 'utf8');
    }
  }

  public function start() {
  	$this->query('START TRANSACTION');
  }
  
  public function commit() {
  	$this->query('COMMIT');
  }
  
  public function rollback() {
  	$this->query('ROLLBACK');
  }
  
  public static function getConnection() {
    return new Db;
  }

  public function query($query) {
    $result = mysqli_query(self::$connection, $query);
    if (!$result) {
    	$this->rollback();
    	print '<pre>'.$query;
      var_dump(mysqli_error(self::$connection));
      exit;
    }
    return $result;
  }

  public function select($query) {
    $result = mysqli_query(self::$connection, $query);
    
    if ($result) {
      $allResults = array();
      while ($row = mysqli_fetch_array($result)) {
        $allResults[] = $row;
      }
      return $allResults;
    } else {
      return false;
    }
  }
  
  public function selectOne($query) {
    $result = $this->select($query);
    return $result[0];
  }

  public function sanitizeData($data) {
    if (is_array($data)) {
      $cleanData = array();
      foreach ($data as $key => $el) {
        $cleanData[$key] = $this->sanitizeData($el);
      }
      return $cleanData;
    } else if (is_null($data)) {
      return "NULL";
    } else if ($data instanceof DbExpr) {
      return $data;
    } else {
      $clean = "'".mysqli_real_escape_string(self::$connection, $data)."'";
      return $clean;
    }
  } 
  
  public function addQuotes($val) {
  	return "`$val`";
  }
  
  public function insert($table, $data) {
    $data = $this->sanitizeData($data);
    $keys = array_map(array($this, 'addQuotes'),array_keys($data));
    $query = 'INSERT INTO `' . $table .'`' 
        . ' (' . implode(', ', $keys) . ')'
        . ' VALUES (' . implode(', ', $data) . ')'
    ;
    
    $result = $this->query($query);
    if (!$result) return false;
    
    return mysqli_insert_id(self::$connection);
    
  }
  
  public function update($table, $data, $where) {
    $data = $this->sanitizeData($data);
    
    $update = array();
    
    foreach($data as $key => $value) {
        $update[] = $key . '=' . $value;
    }
    
    $query = '
        UPDATE ' . $table . '
        SET ' . implode(', ', $update) . '
        WHERE ' . $where . '
    ';
    
    return $this->query($query);
    
  }
}
